package com.geekhalo.demo.mq.disorder.fix.c2;

import com.geekhalo.demo.mq.disorder.OrderCreatedEvent;
import com.geekhalo.demo.mq.event.fix.OrderPaidEvent;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionalEventListener;


@Service
public class RocketMQProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @TransactionalEventListener
    public void handle(OrderCreatedEvent event){
        Long orderId = event.getOrderId();
        Message<OrderCreatedEvent> message = MessageBuilder.withPayload(event)
                .setHeader(RocketMQHeaders.KEYS, orderId) // 设置 Sharding Key，即订单ID
                .setHeader(RocketMQHeaders.TAGS, "OrderCreatedEvent") // 设置 Tag
                .build();
        // 发送至统一的 order_event_topic
        rocketMQTemplate.send("order_event_topic", message);
    }

    @TransactionalEventListener
    public void handle(OrderPaidEvent event){
        Long orderId = event.getOrderId();
        Message<OrderPaidEvent> message = MessageBuilder.withPayload(event)
                .setHeader(RocketMQHeaders.KEYS, orderId) // 设置 Sharding Key，即订单ID
                .setHeader(RocketMQHeaders.TAGS, "OrderCreatedEvent") // 设置 Tag
                .build();
        // 发送至统一的 order_event_topic
        rocketMQTemplate.send("order_event_topic", message);
    }
}